package com.fhz.a2102shopjava.ui.details;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.fhz.a2102shopjava.MainActivity;
import com.fhz.a2102shopjava.callback.ApiResponse;
import com.fhz.a2102shopjava.databinding.ActivityDetailsBinding;
import com.fhz.a2102shopjava.entity.Banner;
import com.fhz.a2102shopjava.entity.GoodsInfo;
import com.fhz.a2102shopjava.entity.ResponseBean;
import com.fhz.a2102shopjava.entity.ShoppingCart;
import com.fhz.a2102shopjava.ui.login.ui.login.LoginActivity;
import com.fhz.a2102shopjava.util.ImageLoader;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;


import com.fhz.a2102shopjava.R;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.ChatManager;
import com.hyphenate.chat.Message;
import com.hyphenate.helpdesk.callback.Callback;
import com.hyphenate.helpdesk.easeui.util.IntentBuilder;
import com.tencent.mmkv.MMKV;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;

/**
 * 产品详情页
 */
@AndroidEntryPoint
public class DetailsActivity extends AppCompatActivity {

    private static final String TAG = "DetailsActivity";
    private ActivityDetailsBinding binding;

    DetailsViewModel mDetailsViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityDetailsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mDetailsViewModel = new ViewModelProvider(this).get(DetailsViewModel.class);
        getBundle();

        ChatClient.getInstance().register("3", "123456", new Callback(){
            @Override
            public void onSuccess() {
                ChatClient.getInstance().login("3", "123456", new Callback(){
                    @Override
                    public void onSuccess() {
                        System.out.println("登录成功!");
                    }

                    @Override
                    public void onError(int code, String error) {
                        System.out.println(error);
                    }

                    @Override
                    public void onProgress(int progress, String status) {
                        System.out.println(status);
                    }
                });
            }

            @Override
            public void onError(int code, String error) {
                System.out.println(error);
            }

            @Override
            public void onProgress(int progress, String status) {
                System.out.println(status);
            }
        });


        ChatClient.getInstance().getChat().addMessageListener(new ChatManager.MessageListener() {
            @Override
            public void onMessage(List<Message> list) {
                //收到普通消息
                System.out.println(list.size());
            }

            @Override
            public void onCmdMessage(List<Message> list) {
                //收到命令消息，命令消息不存数据库，一般用来作为系统通知，例如留言评论更新，
                //会话被客服接入，被转接，被关闭提醒
            }

            @Override
            public void onMessageStatusUpdate() {
                //消息的状态修改，一般可以用来刷新列表，显示最新的状态
                System.out.println("状态");
            }

            @Override
            public void onMessageSent() {
                //发送消息后，会调用，可以在此刷新列表，显示最新的消息
                System.out.println("列表");
            }
        });



        binding.detailsGoodsKefu.setOnClickListener(v ->{
            if(ChatClient.getInstance().isLoggedInBefore()){
                //已经登录，可以直接进入会话界面
                Intent intent = new IntentBuilder(this)
            .setServiceIMNumber("kefuchannelimid_987834") //获取地址：kefu.easemob.com，“管理员模式 > 渠道管理 > 手机APP”页面的关联的“IM服务号”
                        .build();
                startActivity(intent);
            }else{
                //未登录，需要登录后，再进入会话界面
                System.out.println("先登录!");
                Toast.makeText(this, "请先登录!", Toast.LENGTH_SHORT).show();
            }
        });

    }
    private void setBanner(GoodsInfo goodsInfo) {
        binding.detailGoodsBanner.addBannerLifecycleObserver(this);
        binding.detailGoodsBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
//                Log.i(TAG, "OnBannerClick: ");
//                Toast.makeText(this, "先别点了"+position, Toast.LENGTH_SHORT).show();
            }
        });

        String goodsBanner = goodsInfo.getGoodsBanner();
        String[] split = goodsBanner.split(",");
        List<String> strings = Arrays.asList(split);

        binding.detailGoodsBanner
                .setAdapter(new BannerImageAdapter<String>(strings) {
                    @Override
                    public void onBindView(BannerImageHolder holder, String data, int position, int size) {
                        ImageLoader.load(holder.itemView.getContext(),data,holder.imageView);
                    }
                })
                .setIndicator(new CircleIndicator(this));
    }


    private void setFAB(GoodsInfo goodsInfo) {
        binding.fab.setOnClickListener(view -> {

              //登录以后加入购物车
            MMKV mmkv = MMKV.defaultMMKV();
            String username = mmkv.getString("username", "");
            Integer userId = mmkv.getInt("userId", 0);
            if(username.equals("")){
                Toast.makeText(DetailsActivity.this, "请先登录!", Toast.LENGTH_SHORT).show();
                LoginActivity.launch(this);
                return;
            }
            //发送添加到购物的命令

            ShoppingCart shoppingCart = new ShoppingCart();
//            shoppingCart.setCarId(goodsInfo.getId());
            shoppingCart.setCarCreateTime(String.valueOf(System.currentTimeMillis()));
            shoppingCart.setCarShopName("商家名称");
            shoppingCart.setCarImage(goodsInfo.getGoodsDefaultIcon());
            shoppingCart.setCarNum(1);
            shoppingCart.setCarTitle(goodsInfo.getGoodsDesc());
            shoppingCart.setCarPrice(goodsInfo.getGoodsDefaultPrice());
            shoppingCart.setUserId(userId);
            mDetailsViewModel.addCart(shoppingCart).observe(this, listApiResponse -> {
                if(listApiResponse.code != 1){
                    Snackbar.make(view, "成功添加到购物车!", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }else{
                    Snackbar.make(view, "添加失败!", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });


        });
    }

    private void getBundle() {
        Bundle goodsInfo1 = getIntent().getExtras();
        GoodsInfo goodsInfo = (GoodsInfo) goodsInfo1.getSerializable("goodsInfo");
        Log.d(TAG, "getBundle: "+goodsInfo1);

        setBanner(goodsInfo);

        setTitle(goodsInfo);

        setContentDetails(goodsInfo);

        setFAB(goodsInfo);

    }

    private void setContentDetails(GoodsInfo goodsInfo) {
        binding.detailsTitle.setText(goodsInfo.getGoodsDesc());
        binding.detailsGoodsPrice.setText(String.valueOf(goodsInfo.getGoodsDefaultPrice()));
        ImageLoader.load(this,goodsInfo.getGoodsDetailOne(),binding.detailsOne);
        ImageLoader.load(this,goodsInfo.getGoodsDetailTwo(),binding.detailsTwo);
    }

    private void setTitle(GoodsInfo goodsInfo) {
        binding.detailGoodsTitle.setText(goodsInfo.getGoodsDesc().substring(0,6));
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    public static void launch(Context context, GoodsInfo goodsInfo){
        Intent intent = new Intent(context, DetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("goodsInfo",goodsInfo);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

}